import storage from 'good-storage'
import { PLAY_HISTORY_KEY } from '@/common/config'
import { getAlbum } from 'network/request'

async function getSongImg(id, albumId) {
    if (albumId == undefined || albumId == null) {
        throw new Error('need albumId')
    }
    const { songs } = await getAlbum(albumId)
    let song = songs.find(({ id: songId }) => songId === id) || {}
    if (song != null && song != {} && song.al != null) {
        return song.al.picUrl
    }
    return ''
}

export default {
    // 整合歌曲信息 并且开始播放
    async startSong({ commit, state }, rawSong) {
        // 浅拷贝一份 改变引用
        // 1.不污染元数据
        // 2.单曲循环为了触发watch
        const song = Object.assign({}, rawSong)
        if (!song.img) {
            if (song.albumId) {
                song.img = await getSongImg(song.id, song.albumId)
            }
        }
        commit('setCurrentSong', song)
        commit('setPlayingState', true)
        // 历史记录
        const playHistoryCopy = state.playHistory.slice()
        const findedIndex = playHistoryCopy.findIndex(({ id }) => song.id === id)
        if (findedIndex !== -1) {
            // 删除旧那一项
            playHistoryCopy.splice(findedIndex, 1)
        }
        // 插入到最前面
        playHistoryCopy.unshift(song)
        commit('setPlayHistory', playHistoryCopy)
        storage.set(PLAY_HISTORY_KEY, playHistoryCopy)
    },
    // 清除当前歌曲
    clearCurrentSong({ commit }) {
        commit('setCurrentSong', {})
        commit('setPlayingState', false)
        commit('setCurrentTime', 0)
    },
    // 清除当前播放列表
    clearPlaylist({ commit, dispatch }) {
        commit('setPlaylist', [])
        dispatch('clearCurrentSong')
    },
    // 清除播放历史记录
    clearHistory({ commit }) {
        const history = []
        commit('setPlayHistory', history)
        storage.set(PLAY_HISTORY_KEY, history)
    },
    // 添加歌曲到当前播放列表
    addToPlaylist({ commit, state }, song) {
        const { playlist } = state
        const copy = playlist.slice()
        if (!copy.find(({ id }) => id === song.id)) {
            copy.unshift(song)
            commit('setPlaylist', copy)
        }
    }
}